<template>
  <el-dialog v-bind="dialog" :visible.sync="dialog.visible" class="menu-dialog" @open="dialogOpen">
    <el-form v-bind="form" label-position="top">
      <el-form-item prop="menuType" label="菜单类型:" class="menuType-group">
        <el-radio-group v-model="form.model.menuType">
          <el-radio label="1">系统</el-radio>
          <el-radio label="2">菜单</el-radio>
          <el-radio label="3">按钮</el-radio>
          <el-radio label="4">字段</el-radio>
          <el-radio label="5">页面</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="parentId" label="上级页面:">
        <el-select ref="select" clearable :value="selectLabel" placeholder="请选择上级页面,不选择则在根目录创建" @clear="selectClear">
          <el-option :value="form.model.parentId" style="height: unset">
            <el-tree :data="treeData" v-bind="tree" @node-click="handleNodeClick" />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="name" label="菜单名称:">
        <el-input v-model="form.model.name" />
      </el-form-item>
      <el-form-item prop="component" label="前端组件:">
        <el-input v-model="form.model.component" />
      </el-form-item>

      <el-form-item prop="status" label="状态:">
        <el-switch v-model="form.model.status" active-color="#E5E5E5" :active-text="['禁用', '启用'][form.model.status]" inactive-color="#304F9C" />
        <!-- <span>{{}}</span> -->
      </el-form-item>
      <el-form-item prop="sort" label="排序:">
        <el-input v-model.number="form.model.sort" />
      </el-form-item>

      <el-form-item
        v-for="(item, idx) in form.model.url"
        :key="idx"
        :rules="{
          required: true,
          message: `请输入权限标识${idx + 1}`,
          trigger: 'blur'
        }"
        :prop="`url.${idx}.value`"
        :label="`权限地址${idx + 1}:`"
      >
        <el-input v-model="item.value" style="width: 65%; margin-right: 10px" />
        <div style="display: inline-block">
          <el-button icon="el-icon-plus" round plain type="primary" size="mini" @click.prevent="addUrl(idx)"> 新增 </el-button>
          <el-button v-if="form.model.url.length > 1" icon="el-icon-delete-solid" round plain type="danger" size="mini" @click.prevent="deleteUrl(idx)" />
        </div>
      </el-form-item>

      <el-form-item v-if="form.model.menuType == 1 || form.model.menuType == 2" prop="icon" label="图标:">
        <el-input v-model="form.model.icon" />
      </el-form-item>
    </el-form>
    <el-button slot="footer" size="small" type="primary" @click="submit">确 认</el-button>
  </el-dialog>
</template>

<script>
import { internetApi } from '@/api/api'

export default {
  props: {
    treeData: {
      type: Array,
      default: () => []
    },
    treeList: {
      type: Array,
      default: () => []
    },
    update: Function
  },
  data() {
    return {
      //弹窗相关的属性
      dialog: {
        visible: false,
        title: '新建菜单',
        width: '90%',
        closeOnClickModal: false
      },
      //form表单相关的参数
      form: {
        ref: 'form',
        model: {
          id: null,
          parentId: '0',
          name: null,
          component: null,
          menuType: '1',
          status: true,
          url: null,
          sort: null,
          icon: null
        },
        labelWidth: '90px',
        size: 'small',
        rules: {
          menuType: [{ required: true, message: '菜单类型不能为空', trigger: 'change' }],
          name: [
            { required: true, message: '菜单名称不能为空', trigger: 'blur' },
            { min: 2, max: 20, message: '2-20个字之间', trigger: 'blur' }
          ],
          component: [
            { required: true, message: '唯一编码不能为空', trigger: 'blur' },
            { max: 200, message: '200个字以内', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '排序不能为空', trigger: 'blur' },
            { type: 'number', min: 1, max: 127, message: '请输入1-127之间的数字', trigger: 'blur' }
          ],
          // url: [
          //   { required: true, message: '权限地址不能为空', trigger: 'blur' },
          //   { max: 200, message: '200个字以内', trigger: 'blur' }
          // ],
          icon: [
            { required: true, message: '图标不能为空', trigger: 'blur' },
            { max: 50, message: '50个字以内', trigger: 'blur' }
          ]
        }
      },
      //el-tree相关的参数
      tree: {
        props: {
          children: 'children',
          label: 'name'
        },
        expandOnClickNode: false,
        nodeKey: 'id'
      },
      //select展示选中的上级名称
      selectLabel: ''
    }
  },

  methods: {
    // 新增权限地址
    addUrl(idx) {
      this.form.model.url.splice(idx + 1, 0, { value: '' })
    },
    // 删除权限地址
    deleteUrl(idx) {
      this.form.model.url.splice(idx, 1)
    },
    // 权限地址：编辑/新增格式处理
    arrToStr(array) {
      let str = ''
      array.forEach((el) => {
        str += el.value + ','
      })
      if (str) {
        return str.substring(0, str.length - 1)
      }
      return ''
    },
    //清空单选框时
    selectClear() {
      this.form.model.parentId = '0'
      this.selectLabel = ''
    },
    //树节点点击
    handleNodeClick(data) {
      this.$refs.select.blur()
      this.selectLabel = data.name
      this.form.model.parentId = data.id
    },
    //确认按钮
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const model = Object.assign({}, this.form.model)
          model.url = this.arrToStr(this.form.model.url)

          if (this.form.model.id) {
            await this.$request(internetApi.updateMenu, model)
          } else {
            await this.$request(internetApi.addMenu, model)
          }
          this.update()
          this.$message.success('操作成功')
          this.dialog.visible = false
        }
      })
    },
    open(type, row) {
      if (type === 'edit') {
        //编辑
        this.form.model.id = row.id
        this.form.model.parentId = row.parentId
        this.form.model.name = row.name
        this.form.model.component = row.component
        this.form.model.menuType = row.menuType
        this.form.model.status = row.status
        this.form.model.url = this.strToArr(row.url)
        this.form.model.sort = row.sort
        this.form.model.icon = row.icon
        const tmp = this.treeList.filter((item) => {
          return item.id === row.parentId
        })
        this.selectLabel = tmp.length ? tmp[0].name : ''
        this.dialog.title = '编辑菜单'
      } else {
        //新增
        this.form.model.id = null
        this.form.model.parentId = row.id || '0'
        this.form.model.name = null
        this.form.model.component = null
        this.form.model.menuType = '1'
        this.form.model.status = true
        this.form.model.url = [{ value: '' }]
        this.form.model.sort = null
        this.form.model.icon = null
        this.selectLabel = row.name || ''
        this.dialog.title = '新建菜单'
      }
      this.dialog.visible = true
    },
    // 权限地址：编辑格式处理
    strToArr(data, first) {
      const ds = data.split(',') || []
      const newArr = ds.map((item) => {
        return {
          value: item
        }
      })
      if (first) {
        return newArr[0].value
      } else {
        // newArr.shift()
        return newArr
      }
    },
    //弹窗打开时，清除所有校验
    dialogOpen() {
      //dialog是懒加载，所以要用$nextTick
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select-dropdown__item {
  padding: 0;
  &.selected {
    font-weight: normal;
  }
}
.el-select {
  display: block;
}
.el-tree {
  padding-right: 10px;
}
.el-dialog__wrapper ::v-deep.el-dialog {
  max-width: 450px;
}
.el-switch ::v-deep.el-switch__label.is-active {
  color: #303133;
}

.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 8px;
}

::v-deep.el-form--label-top .el-form-item__label {
  padding: 0 0 5px;
}

::v-deep.menu-dialog .el-dialog__body {
  padding-top: 0;
  padding-bottom: 0;
}

.menuType-group .el-form-item__content {
  display: flex;
  justify-content: center;
}
</style>
